package leetcode100;

public class lc024 {
    public static void main(String[] args) {
        ListNode node1 = new ListNode(2);
        ListNode node2 = new ListNode(4);
        ListNode node3 = new ListNode(5);

        node2.next = node3;
        node1.next = node2;


        ListNode node4 = new ListNode(5);
        ListNode node5 = new ListNode(6);
        ListNode node6 = new ListNode(4);

        node5.next = node6;
        node4.next = node5;

        ListNode res = new lc024().addTwoNumbers(node1, node4);
        res.visit();

    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode cur1 = l1;
        ListNode cur2 = l2;
        ListNode cur3 = null;
        ListNode l3 = null;
        int flag = 0;
        l3 = new ListNode((cur1.val + cur2.val) % 10);
        cur3 = l3;
        if (cur1.val+cur2.val>=10) {
            flag = 1;
        }
        cur2 = cur2.next;
        cur1 = cur1.next;

        while (cur1 != null || cur2 != null) {
            ListNode newNode = new ListNode(((cur1==null?0:cur1.val)
                    +(cur2==null?0:cur2.val)+flag)%10);
            flag = (cur1==null?0:cur1.val)
                    +(cur2==null?0:cur2.val)
                    +flag >=10 ? 1:0;
            cur3.next = newNode;
            cur3 = cur3.next;
            if (cur1!=null)
                cur1 = cur1.next;
            if (cur2!=null)
                cur2 = cur2.next;

        }
        if (flag==1) {
            cur3.next = new ListNode(flag);
        }
        return l3;
    }
}
